package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.GoodsBase;
import cn.com.dashihui.web.dao.GoodsBaseImages;
import cn.com.dashihui.web.dao.GoodsStore;
import cn.com.dashihui.web.service.GoodsBaseService;

/**
 * 平台基础商品管理，基础商品可由各店铺进行复制
 */
public class GoodsBaseController extends BaseController{
	private static final Logger logger = Logger.getLogger(GoodsBaseController.class);
	private GoodsBaseService service = Duang.duang(new GoodsBaseService());
	/**
	 * 转到商品列表页面
	 */
	public void index(){
		render("index.jsp");
	}
	/**
	 * 列表页面异步请求数据
	 */
	public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		int s = getParaToInt("s",0);
		int c1 = getParaToInt("c1",0);
		int c2 = getParaToInt("c2",0);
		int c3 = getParaToInt("c3",0);
		int c4 = getParaToInt("c4",0);
		String keyword = getPara("k");
		renderResult(0,service.findByPage(pageNum,pageSize,s,c1,c2,c3,c4,keyword));
	}
	
	/**
	 * 商品添加页面
	 */
	public void toAdd(){
		render("add.jsp");
	} 
	/**
	 * 添加商品
	 */
	public void doAdd(){
		//商品名称
		String name = getPara("name");
		//所属类别：
		String categoryonid = getPara("categoryonid");
		String categorytwid = getPara("categorytwid");
		String categorythid = getPara("categorythid");
		String categoryfoid = getPara("categoryfoid");
		//商品品牌
		String brandid = getPara("brandid","0");
		//商品规格说明
		String spec = getPara("spec");
		//短简介
		String shortInfo = getPara("shortInfo");
		//市场价格
		String marketPrice = getPara("marketPrice");
		//销售价格
		String sellPrice = getPara("sellPrice");
		//状态
		int state = getParaToInt("state",1);
		if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else if(StrKit.isBlank(categoryonid)||StrKit.isBlank(categorytwid)||StrKit.isBlank(categorythid)||StrKit.isBlank(categoryfoid)){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(spec)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(marketPrice)){
			renderResult(4);
			return;
		}else if(StrKit.isBlank(sellPrice)){
			renderResult(5);
			return;
		}else{
			GoodsBase goods=new GoodsBase()
					.set("name", name)
					.set("categoryonid", Integer.valueOf(categoryonid).intValue())
					.set("categorytwid", Integer.valueOf(categorytwid).intValue())
					.set("categorythid", Integer.valueOf(categorythid).intValue())
					.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
					.set("brandid", brandid)
					.set("spec", spec)
					.set("shortInfo", shortInfo)
					.set("marketPrice", marketPrice)
					.set("sellPrice", sellPrice)
					.set("state", state);
			//保存
			if(service.add(goods)){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}

	/**
	 * 修改商品信息页面
	 */
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}

	/**
	 * 修改商品信息并保存
	 */
	public void doEdit(){
		String id = getPara("goodsid");
		//商品名称
		String name = getPara("name");
		//所属类别：
		String categoryonid = getPara("categoryonid");
		String categorytwid = getPara("categorytwid");
		String categorythid = getPara("categorythid");
		String categoryfoid = getPara("categoryfoid");
		//商品品牌
		String brandid = getPara("brandid","0");
		//商品规格说明
		String spec = getPara("spec");
		//短简介
		String shortInfo = getPara("shortInfo");
		//市场价格
		String marketPrice = getPara("marketPrice");
		//销售价格
		String sellPrice = getPara("sellPrice");
		//状态
		int state = getParaToInt("state",1);
		if(StrKit.isBlank(id)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else if(StrKit.isBlank(categoryonid)||StrKit.isBlank(categorytwid)||StrKit.isBlank(categorythid)||StrKit.isBlank(categoryfoid)){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(spec)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(marketPrice)){
			renderResult(4);
			return;
		}else if(StrKit.isBlank(sellPrice)){
			renderResult(5);
			return;
		}else{
			GoodsBase goods=new GoodsBase()
					.set("id", id)
					.set("name", name)
					.set("categoryonid", Integer.valueOf(categoryonid).intValue())
					.set("categorytwid", Integer.valueOf(categorytwid).intValue())
					.set("categorythid", Integer.valueOf(categorythid).intValue())
					.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
					.set("brandid", brandid)
					.set("spec", spec)
					.set("shortInfo", shortInfo)
					.set("marketPrice", marketPrice)
					.set("sellPrice", sellPrice)
					.set("state", state);
			//保存
			if(service.update(goods)){
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;
			}
		}
		renderFailed();
	}

	/**
	 * 商铺产品删除指定id的商品记录<br/>
	 * 不删除图片
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&GoodsStore.me().deleteById(id)){
			logger.info("删除商品【"+id+"】");
			renderSuccess();
			return;
		}
		renderFailed();
			
	}

	/**
	 * 商铺产品修改详细内容页面
	 */
	public void toDetailEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("editorDetail.jsp");
	}

	/**
	 * 商铺产品详情页面富文本编辑内容修改并保存数据
	 */
	public void doDetailEdit(){
		String id = getPara("id");
		String describe = getPara("describe");
		if(StrKit.isBlank(id)){
			renderResult(1);
			return;
		}
		GoodsBase goods = new GoodsBase()
				.set("id", Integer.valueOf(id).intValue())
				.set("describe", describe);
		if(service.update(goods)){
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 商铺产品文本编辑中图片上传
	 */
	public void uploadimg(){
		UploadFile thumb = getFile();
		Map<String,Object> map = new HashMap<String,Object>();  
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
				map.put("error", 0);  
				map.put("url",PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));  
				renderJson(map);
		        return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);  
				map.put("message","图片上传失败");  
				renderJson(map);
			}
		}else{
			map.put("error", 1);  
			map.put("message","图片为空");  
			renderJson(map);
		}
	}
	
	/**
	 * 图片列表
	 */
	public void imageIndex(){
    	setAttr("goodsid", getParaToInt(0));
        render("imageList.jsp");
    }
    
	/**
	 * 图片分页
	 */
    public void imagePage(){
    	renderSuccess(service.findAllImages(getParaToInt(0)));
    }
    
    /**
     * 图片排序
     */
    public void doImageSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		service.sortImages(sortMap);
    		renderSuccess();
    		return;
    	}
    	renderFailed();
    }
    
    /**
     * 添加图片
     */
	public void toImageAdd(){
		setAttr("goodsid",getPara(0));
		render("imageAdd.jsp");
	}
	
	/**
	 * 添加图片
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageAdd(){
		UploadFile thumb = getFile("thumb");
		int goodsid = getParaToInt("goodsid");
		//保存
		//如果上传了图片，则上传至FTP，并记录图片文件名
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_IMAGES);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
			} catch (IOException e) {
				e.printStackTrace();
				renderResult(2);
				return;
			}
			GoodsBaseImages image = new GoodsBaseImages().set("goodsid", goodsid).set("thumb", dir.concat(thumbFileName));
			if(service.addImage(image)){
				renderSuccess(image);
				return;
			}
		}else{
			renderResult(1);
			return;
		}
	}
	
	/**
	 * 设置图片为商品LOGO
	 * @return -1：异常，0：成功
	 */
	public void doSetImageLogo(){
		int id = getParaToInt(0,0);
		int goodsid = getParaToInt("goodsid");
		if(id!=0&&service.setImageLogo(goodsid,id)){
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 * 删除图片
	 * @return -1：删除失败，0：删除成功
	 */
	public void doImageDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&service.delImage(id)){
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
